package com.example.hetong_system.controller;

import com.example.hetong_system.model.PaymentPlan;
import com.example.hetong_system.repository.PaymentPlanRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/auth/payment")
public class PaymentPlanController {

    private static final Logger logger = LoggerFactory.getLogger(PaymentPlanController.class);

    @Autowired
    private PaymentPlanRepository paymentPlanRepository;

    /**
     * 查询支付状态（供前端轮询）
     */
    @GetMapping("/check-status/{outTradeNo}")
    public ResponseEntity<ApiResponse> checkPaymentStatus(@PathVariable String outTradeNo) {
        try {
            // 参数校验
            if (outTradeNo == null || outTradeNo.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(new ApiResponse(false, "订单号不能为空", null));
            }

            // 查询支付计划
            Optional<PaymentPlan> planOptional = paymentPlanRepository.findByOutTradeNo(outTradeNo);

            if (planOptional.isEmpty()) {
                logger.warn("未找到支付记录，订单号: {}", outTradeNo);
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse(false, "未找到支付记录", null));
            }

            PaymentPlan plan = planOptional.get();
            // 构建支付状态响应
            PaymentStatus status = new PaymentStatus(
                    plan.getIsExecuted(),
                    plan.getPayTime()
            );

            return ResponseEntity.ok(
                    new ApiResponse(true, "查询成功", status)
            );

        } catch (Exception e) {
            logger.error("查询支付状态失败，订单号: {}", outTradeNo, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "查询失败：" + e.getMessage(), null));
        }
    }

    // 标准化API响应结构
    private static class ApiResponse {
        private final boolean success;
        private final String message;
        private final Object data;

        public ApiResponse(boolean success, String message, Object data) {
            this.success = success;
            this.message = message;
            this.data = data;
        }

        // getters 必须提供，否则Jackson无法序列化
        public boolean isSuccess() { return success; }
        public String getMessage() { return message; }
        public Object getData() { return data; }
    }

    // 支付状态数据结构
    private static class PaymentStatus {
        private final boolean paid;
        private final Object payTime; // 使用Object兼容LocalDateTime的JSON序列化

        public PaymentStatus(boolean paid, Object payTime) {
            this.paid = paid;
            this.payTime = payTime;
        }

        // getters
        public boolean isPaid() { return paid; }
        public Object getPayTime() { return payTime; }
    }
}